import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import routeModules from '@/router/modules'
import { getLocalStorage } from '@/assets/utils/utils'
import { message } from 'ant-design-vue'
import { App } from 'vue'

const router = createRouter({
  history: createWebHashHistory(),
  routes: routeModules as unknown as RouteRecordRaw[],
  scrollBehavior: () => ({ left: 0, top: 0 })
})

router.beforeEach((to, from, next) => {
  document.title = to.meta.title ? (to.meta.title as string) : '后台管理'
  if (to.path === '/login') {
    next()
  } else if (to.path === '/home/manager') {
    if (getLocalStorage('role') === 'manager') {
      next()
    } else {
      next(false)
      message.error('当前身份不是管理员！')
    }
  } else {
    if (getLocalStorage('token')) {
      next()
    } else next('/login')
  }
})

const installRouter = (app: App) => {
  app.use(router)
}

export default installRouter
